import React, { Component } from 'react'
import styles from './index.module.scss'
import {
  Breadcrumb,
  Button,
  Card,
  Form,
  Image,
  Table,
  Tag,
  message
} from 'antd'
import { Link } from 'react-router-dom'
import Radio from 'antd/es/radio/radio'
import { articleState } from 'api/constant'
import { DatePicker } from 'antd'
import { delArticle, getArticleList } from '../../api/article'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons'
import errorImg from 'assets/error.png'
import Modal from 'antd/es/modal/Modal'
import moment from 'moment'
import ArticleChannels from '../../components/ArticleChannels'

const { RangePicker } = DatePicker
const columns = (props) => [
  {
    title: '封面',
    dataIndex: ['cover', 'images'],
    render: function (text) {
      if (text.length === 0)
        return <Image preview={false} width={200} src={errorImg} />
      return <Image width={200} src={text[0]} />
    }
  },
  {
    title: '标题',
    dataIndex: 'title',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'status',
    render(text) {
      const state = articleState.find((item) => item.id === text)
      return <Tag color={state.color}>{state.name}</Tag>
    }
  },
  {
    title: '发布时间',
    dataIndex: 'pubdate'
  },
  {
    title: '阅读数',
    dataIndex: 'read_count'
  },
  {
    title: '评论数',
    dataIndex: 'comment_count'
  },
  {
    title: '点赞数',
    dataIndex: 'like_count'
  },
  {
    title: '操作',
    render(row) {
      return (
        <div>
          <Button
            style={{ margin: '0 5px' }}
            type='primary'
            shape='circle'
            onClick={() => {
              props.handleEdit(row)
            }}
            icon={<EditOutlined />}></Button>
          <Button
            type='danger'
            shape='circle'
            onClick={() => {
              props.showModal(row)
            }}
            icon={<DeleteOutlined />}></Button>
        </div>
      )
    }
  }
]
export default class ArticleList extends Component {
  constructor(props) {
    super(props)
    this.state = {
      tableData: [],
      total_count: 0,
      formData: {
        status: -1,
        channel_id: null,
        begin_pubdate: null,
        end_pubdate: null,
        page: 1,
        per_page: 10
      },
      tableLoading: false
    }
  }

  componentDidMount() {
    this.loadArticleList()
  }

  // 删除文章
  handleDelArticle = async () => {
    this.setState({
      loading: true
    })
    await delArticle(this.state.row.id)
    await this.loadArticleList()
    this.setState({
      loading: false,
      visible: false
    })
    message.success('删除成功')
  }

  // 获取文章列表
  loadArticleList = async () => {
    this.setState({
      tableLoading: true
    })
    if (this.state.formData.status === -1) {
      this.setState(
        {
          formData: {
            ...this.state.formData,
            status: null
          }
        },
        () => {
          this.loadArticleList()
        }
      )
      return
    }
    const {
      data: { results, total_count, page, per_page }
    } = await getArticleList(this.state.formData)
    this.setState({
      tableData: results,
      total_count,
      formData: {
        ...this.state.formData,
        page,
        per_page
      },
      loading: false,
      visible: false,
      row: {},
      tableLoading: false
    })
  }

  onFinish = (val) => {
    val.begin_pubdate =
      val.date &&
      moment(val.date[0]?._d).startOf('day').format('YYYY-MM-DD HH:mm:ss')
    val.end_pubdate =
      val.date &&
      moment(val.date[1]?._d).endOf('day').format('YYYY-MM-DD HH:mm:ss')
    delete val.date
    this.setState(
      {
        formData: {
          ...this.state.formData,
          ...val
        }
      },
      () => {
        this.loadArticleList()
      }
    )
  }

  showModal = (row) => {
    this.setState({
      visible: true,
      row
    })
  }

  shouldComponentUpdate(nextProps, nextState) {
    const { formData } = this.state
    const { formData: nextFormData } = nextState
    if (
      formData.page !== nextFormData.page ||
      formData.per_page !== nextFormData.per_page
    ) {
      return true
    }
    const formDataKeys = Object.keys(formData)
    let flag = true
    formDataKeys.forEach((key) => {
      if (key === 'page' || key === 'per_page') return
      if (formData[key] !== nextFormData[key]) {
        flag = false
      }
    })
    return flag
  }

  handleEdit = (row) => {
    this.props.history.push('/home/articlePublish/' + row.id)
  }

  render() {
    const { visible, loading } = this.state
    return (
      <div className={styles['article']}>
        <Card
          title={
            <Breadcrumb separator='>'>
              <Breadcrumb.Item>
                <Link to={'/home'}>首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>内容管理</Breadcrumb.Item>
            </Breadcrumb>
          }>
          <Form
            onFinish={this.onFinish}
            initialValues={{
              status: -1
            }}>
            <Form.Item name={'status'} label={'状态'}>
              <Radio.Group>
                {articleState.map((item) => {
                  return (
                    <Radio key={item.id} value={item.id}>
                      {item.name}
                    </Radio>
                  )
                })}
              </Radio.Group>
            </Form.Item>
            <Form.Item label={'频道'} name={'channel_id'}>
              <ArticleChannels width={200} />
            </Form.Item>
            <Form.Item label={'日期'} name={'date'}>
              <RangePicker />
            </Form.Item>

            <Button type='primary' htmlType={'submit'}>
              筛选
            </Button>
          </Form>
        </Card>
        <Card title={`根据筛选的数据${this.state.total_count}条`}>
          <Table
            loading={this.state.tableLoading}
            dataSource={this.state.tableData}
            pagination={{
              defaultCurrent: 1,
              total: this.state.total_count,
              defaultPageSize: 10,
              onChange: (page, pageSize) => {
                this.setState(
                  {
                    formData: {
                      ...this.state.formData,
                      page,
                      per_page: pageSize
                    }
                  },
                  () => {
                    this.loadArticleList()
                  }
                )
              }
            }}
            columns={columns({
              showModal: this.showModal,
              handleEdit: this.handleEdit
            })}
            rowKey={'id'}
          />
        </Card>
        <Modal
          visible={visible}
          onOk={this.handleDelArticle}
          onCancel={this.handleCancel}
          footer={[
            <Button key='back' onClick={this.handleCancel}>
              取消
            </Button>,
            <Button
              key='submit'
              type='primary'
              loading={loading}
              onClick={this.handleDelArticle}>
              确定
            </Button>
          ]}>
          确认删除吗?
        </Modal>
      </div>
    )
  }

  handleCancel = () => {
    this.setState({ visible: false })
  }
}
